<template>
  <view class="exam-submission">
   <!-- 参与考试 -->
    <view class="section">
      <view class="section-header">
        <view class="section-title">{{examinationInfo.title}}</view>
        <view class="section-status">
          <u-tag :text="examinationInfo.statusText" type="warning" size="mini" color="#c4996c" bgColor="#faf3ed"></u-tag>
        </view>
      </view>
      <view class="description">
        {{examinationInfo.refer}}
      </view>
      <view class="course-info" @click="handleTitleClick(examinationInfo.courseId)">
        <view class="flex items-center">
          <image class="img" :src="IMG_URL2+'peop/union.svg'" mode="aspectFill" />
          {{examinationInfo.courseName}}
        </view>
        <view>
          <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
        </view>
      </view>
    </view>
    <!--  0视频 1音频 -->
    <view class="section" v-if="examinationInfo.category=='0'">
      <text class="section-title">上传视频</text>
      <view class="upload-area">
        <view class="video-preview" v-if="videoUrl">
          <video :src="videoUrl" class="video"></video>
          <view class="delete-btn" @click.stop="handleDeleteVideo">
            <u-icon name="close" color="#fff" size="24"></u-icon>
          </view>
        </view>
        <view class="upload-box" @click="handleUpload">
          <u-icon name="plus" size="40" color="#999"></u-icon>
        </view>
      </view>
    </view>
    <view class="section" v-if="examinationInfo.category=='1'">
      <text class="section-title">录音上传</text>
      <view class="upload-area">
        <view class="audio-preview" v-if="audioUrl">
          <luchaudio :src="audioUrl" :play.sync="audioPlay" :name="`${examinationInfo.title}答题音频`"></luchaudio>
          <view class="delete-btn1" @click.stop="handleDeleteAudio">
            删除
          </view>
        </view>
      </view>
      <view class="upload-area">
        <view class="audio-box" @click="handleStartRecord" v-if="!isRecording && !audioUrl">
          <u-icon name="mic" size="40" color="#999"></u-icon>
          <text class="audio-tip">点击开始录音</text>
        </view>
        <view class="audio-box recording" v-if="isRecording" @click="handleStopRecord">
          <u-icon name="more-dot-fill" size="40" color="#c4996c"></u-icon>
          <text class="audio-tip">录音中,点击停止</text>
        </view>
      </view>
    </view>
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit" :disabled="loading">
        <up-loading-icon class="loading" color="#fff" size="16" :show="loading"></up-loading-icon>
        <text>提交</text>
      </button>
    </view>
    <view v-if="!AccountStatus" class="w100 submitTips">
			<view class="w100 mt-90 flex justify-center items-center flex-wrap">
				<view class="w100 mt-20 flex justify-center items-center"><image class="logo" :src="IMG_URL2 + 'common/check-circle.svg'" /></view>
				<view class="mt-20 f-24 white titinfo" >提交成功</view>
        <!-- <view class="course-integration">
          <image class="img" :src="IMG_URL2 + 'inventory/money-circle.svg'" mode="aspectFill" />
          <view>获得{{integration}}积分</view>
        </view> -->
			</view>
			<view class="complete-btn" @click="completeFun">完成</view>
		</view>

  </view>
</template>

<script setup>
import { ref } from 'vue'
import { BASE_API,IMG_URL2 } from "@/config";
import { studyApi } from "@/api";
import luchaudio from "./luch-audio.vue";
const videoUrl = ref('')
const audioUrl = ref('')
let AccountStatus = ref(true);
const isRecording = ref(false)
const loading = ref(false);
let examinationQuestionId =ref('')
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
let examinationInfo=ref({
  title:'',
  courseName:'',
  category:'',
  refer:'',
  courseId:''
})
let currentPage=ref('')

// 0待打分 1不通过 2已通过 3未完成
const statusMap = {
  '0': '待打分',
  '1': '不通过',
  '2': '已通过',
  '3': '未完成'
}

const handleTitleClick = (id) => {
  uni.navigateTo({
    url: `/pages/trainingcenter/coursedetails?courseId=${id}&currentPage=${currentPage.value}`
  })
}
const handleUploadAudio = ()=>{
  // 上传录制的音频
  if(!audioUrl.value){
    uni.showToast({
      title: '请先录音',
      icon: 'none'
    })
    return
  }


}
const handleUpload = () => {
  uni.authorize({
    scope: 'scope.camera',
    success() {
      uni.chooseVideo({
        sourceType: ['album'],
        success: (res) => {
          // videoUrl.value = res.tempFilePath
          const filePath = res.tempFilePath;
          // 将二进制数据上传到服务器
          wx.uploadFile({
            url:  BASE_API + '/bg/file/upload',   // 上传的 URL 地址
            filePath: filePath,   // 文件的临时路径
            name: 'file',   // 服务器端接收文件的字段名
            header: {
              'content-type': 'multipart/form-data'   // 设置请求头
            },
            formData: {},
            success: function(res) {
              // 上传成功后的操作
              const response = JSON.parse(res.data)
              if (response.result && response.result.url) {
                videoUrl.value = response.result.url
              }
            },
            fail: function(res) {
              // 上传失败后的操作
              console.log(res);
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: '选择视频失败',
            icon: 'none'
          })
        }
      })

      
    },
    fail() {
      uni.showModal({
        title: '提示',
        content: '请在设置中允许使用摄像头权限',
        success(res) {
          if (res.confirm) {
            uni.openSetting()
          }
        }
      })
    }
  })
}

const handleDeleteVideo = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该视频吗？',
    success: (res) => {
      if (res.confirm) {
        videoUrl.value = ''
      }
    }
  })
}
const completeFun = () => {
	uni.navigateBack({
      delta: 1
  });
}
const handleStartRecord = () => {
  uni.authorize({
    scope: 'scope.record',
    success() {
      recorderManager.start({
        duration: 60000, // 最长录音时间，单位ms
        format: 'mp3'
      })
      isRecording.value = true
    },
    fail() {
      uni.showModal({
        title: '提示',
        content: '请在设置中允许使用麦克风权限',
        success(res) {
          if (res.confirm) {
            uni.openSetting()
          }
        }
      })
    }
  })
}

const handleStopRecord = () => {
  recorderManager.stop()
  isRecording.value = false
}

recorderManager.onStop((res) => {
  audioUrl.value = res.tempFilePath
  wx.uploadFile({
    url: BASE_API + '/bg/file/upload',
    filePath: res.tempFilePath,
    name: 'file',
    header: {
      'content-type': 'multipart/form-data'
    },
    formData: {},
    success: function(res) {
      const response = JSON.parse(res.data)
      if (response.result && response.result.url) {
        audioUrl.value = response.result.url
      }
      
    },
    fail: function(res) {
      console.log('上传失败:', res)
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      })
    }
  })
})

const playAudio = () => {
  innerAudioContext.src = audioUrl.value
  innerAudioContext.play()
}

const handleDeleteAudio = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该录音吗？',
    success: (res) => {
      if (res.confirm) {
        audioUrl.value = ''
      }
    }
  })
}

const handleSubmit = () => {
  if (!videoUrl.value && !audioUrl.value) {
    uni.showToast({
      title: '请上传视频或录音',
      icon: 'none'
    })
    return
  }

  submitAnswer()

}

const submitAnswer = ()=>{
  let params={
    answerUrl:examinationInfo.value.category==0?videoUrl.value:audioUrl.value,
    examinationQuestionId: examinationQuestionId.value
  }
  loading.value = true;
  studyApi.STUDYSUBMITANSWER(params).then((res) => {
    loading.value = false
    if (res.code == 200) {
      AccountStatus.value = false
    }else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }
  })
} 

const getData=()=>{
  let params={
    id: examinationQuestionId.value
  }
  studyApi.STUDYGETEXAMINATIONBYID(params).then(res => {
    if(res.code == 200) {
      examinationInfo.value = {
        ...res.result,
        statusText: res.result.status != null && res.result.status !== undefined ? statusMap[res.result.status] : '未知状态'
      }
      console.log(examinationInfo.value)
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }
  })
}

onLoad((options) => {
  if (options.id) {
    examinationQuestionId.value = options.id
  }
  if(options.currentPage){
    currentPage.value = options.currentPage
  }
  getData()
})
</script>

<style lang="scss" scoped>
.exam-submission {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  .section {
    background-color: #fff;
    padding: 30rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;

    .section-header {
      margin-bottom: 20rpx;
      gap: 20rpx;
    }

    .section-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    .section-status{
      display: flex;
      align-items: center;
    }

    .description {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      margin-bottom: 20rpx;
    }
    .course-info{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .img {
        width: 28rpx;
        height: 28rpx;
        margin-right: 10rpx;
      }
      .chevronright {
        width: 32rpx;
        height: 32rpx;
      }
    }

    .upload-area {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      margin-bottom: 20rpx;

      .upload-box, .audio-box {
        width: 200rpx;
        height: 200rpx;
        background-color: #f5f5f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 12rpx;

        &:active {
          opacity: 0.8;
        }

        &.recording {
          background-color: #faf3ed;
        }

        .audio-tip {
          font-size: 24rpx;
          color: #999;
          margin-top: 10rpx;
        }
      }

      .video-preview, .audio-preview {
        position: relative;
        width: 100%;
        height: 200rpx;
        border-radius: 12rpx;
        overflow: hidden;

        .video {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .audio-player {
          width: 100%;
          height: 100%;
          background-color: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .delete-btn {
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          width: 40rpx;
          height: 40rpx;
          color: rgba(213, 73, 65, 1);
          border:1rpx solid rgba(213, 73, 65, 1);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .delete-btn1 {
          position: absolute;
          top: 60rpx;
          right: 20rpx;
          // width: 40rpx;
          // height: 40rpx;
          color: rgba(213, 73, 65, 1);
          border:1rpx solid rgba(213, 73, 65, 1);
          // border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #c4996c;
      color: #fff;
      border: none;
      border-radius: 44rpx;
      font-size: 32rpx;
      display: flex;
      justify-content: center;
      &:active {
        opacity: 0.9;
      }
    }
  }
}
.submitTips {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  background-color: rgba(255, 255, 255, 1);


  .submitTipsBox {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .complete-btn {
    background: rgba(253, 236, 219, 1);
    font-family: PingFang SC;
    font-size: 16px;
    font-weight: 600;
    line-height: 24px;
    text-align: center;
    color: rgba(145, 74, 0, 1);

    width: 319px;
    margin: 90px auto 0px;
    padding: 12px 20px 12px 20px;
    box-sizing: border-box;
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
  